<template>
  <Container class="brand-list">
    <div class="container-header" slot="header">
      <Form class="search">
        <Row>
          <Col span="7">
            <FormItem label="单号中策云" class="w130">
              <Input 
                class="start"
                v-model.trim="list.form.purchOrderSn"
                placeholder="单号中策云"
                @on-enter="onSearchBtnClick">
              </Input>
            </FormItem>
            <FormItem label="销售订单ERP" class="w130">
              <Input 
                class="start"
                v-model.trim="list.form.erpOrderSn"
                placeholder="销售订单(ERP)"
                @on-enter="onSearchBtnClick">
              </Input>
            </FormItem>
            <FormItem label="经销商单位名称前鹏" class="w130">
              <Input 
                class="start"
                v-model.trim="list.form.fxDistributorName"
                placeholder="经销商单位名称(前鹏)"
                @on-enter="onSearchBtnClick">
              </Input>
            </FormItem>
            <FormItem label="部门选择" class="w130">
              <Cascader 
                :data="departmentTree"
                :change-on-select='true'
                v-model="value"
                @on-change="onSelectDpt"
                placeholder="请选择地区"
              ></Cascader>
            </FormItem>
            <FormItem label="经销商单位编号前鹏" class="w130">
              <Input 
                class="start"
                v-model.trim="list.form.fxDistributorSn"
                placeholder="经销商单位编号前鹏"
                @on-enter="onSearchBtnClick">
              </Input>
            </FormItem>
          </Col>
          <Col span="5">
            <FormItem label="单号前鹏">
              <Input 
                class="start"
                v-model.trim="list.form.fxSn"
                placeholder="单号"
                @on-enter="onSearchBtnClick">
              </Input>
            </FormItem>
            <FormItem label="收货地址">
              <Input 
                class="start"
                v-model.trim="list.form.orderSn"
                placeholder="单号"
                @on-enter="onSearchBtnClick">
              </Input>
            </FormItem>
            <FormItem label="出库时间">
              <DatePicker 
                v-model="list.form.date"
                format="yyyy-MM-dd" 
                type="daterange" 
                placement="bottom-start" 
                placeholder="选择日期"
                @on-enter="onSearchBtnClick"></DatePicker>
            </FormItem>
            <FormItem label="经销商">
              <!-- <Input 
                class="start"
                v-model.trim="list.form.superiorDistributorName"
                placeholder="经销商"
                @on-enter="onSearchBtnClick">
              </Input> -->
              <SelectList v-model='list.form.distributorId' ref="dealerList" listType='dealerList' />
            </FormItem>
          </Col>
          <Col span="5">
            <FormItem label="创建时间">
              <DatePicker 
                v-model="list.form.crDate"
                format="yyyy-MM-dd" 
                type="daterange" 
                placement="bottom-start" 
                placeholder="选择日期"
                @on-enter="onSearchBtnClick"></DatePicker>
            </FormItem>
            <FormItem label="收货人">
              <Input 
                class="start"
                v-model.trim="list.form.receiverContactName"
                placeholder="收货人"
                @on-enter="onSearchBtnClick">
              </Input>
            </FormItem>
            <FormItem label="快递公司">
              <Input 
                class="start"
                v-model.trim="list.form.deliveryCo"
                placeholder="快递公司"
                @on-enter="onSearchBtnClick">
              </Input>
            </FormItem>
            <FormItem label="出库单ERP">
              <Input 
                class="start"
                v-model.trim="list.form.erpStockOutSn"
                placeholder="出库单(ERP)"
                @on-enter="onSearchBtnClick">
              </Input>
            </FormItem>
          </Col>
          <Col span="5">
            <FormItem label="收货电话">
              <Input 
                class="start"
                v-model.trim="list.form.receiverContactPhone"
                placeholder="收货电话"
                @on-enter="onSearchBtnClick">
              </Input>
            </FormItem>
            <FormItem label="商品">
              <Input 
                class="start"
                v-model.trim="list.form.title"
                placeholder="商品"
                @on-enter="onSearchBtnClick">
              </Input>
            </FormItem>
            <FormItem label="快递单号">
              <Input 
                class="start"
                v-model.trim="list.form.deliverySn"
                placeholder="快递单号"
                @on-enter="onSearchBtnClick">
              </Input>
            </FormItem>
            <FormItem label="门店">
              <StoreSelect v-model="list.form.storeId" :src="src" :distributorId="list.form.distributorId" :provinceId="list.form.provinceId" :cityId="list.form.cityId" :areaId="list.form.areaId"></StoreSelect>
            </FormItem>
          </Col>
          <Col class-name="search" span="2">
            <Button class="btn-search large" type="primary" icon="ios-search" @click="onSearchBtnClick"></Button>
          </Col>
        </Row>
      </Form>
    </div>
    <Tabs v-model="tab">
      <Button
        size="large" class="item" slot="extra"
        icon="ios-flag"
        @click="onBatch">批量编辑直发费用</Button>
        <export-btn 
          :param="exportParam" 
          url='/order/direct_delivery/export' 
          class="item" 
          slot="extra"></export-btn>
      <TabPane label="工厂直发" name="tab1">
        <Table
          :height="options.tableHeight"
          stripe
          :columns="list.columns"
          :data="list.data"
          @on-selection-change="onSelectionChange"
          no-data-text="亲，没有找到相关记录哦！~"
        ></Table>
        <div class="pager">
          <Page
            :total="list.totalItem"
            :current="list.currentPage"
            :page-size="list.pageSize"
            @on-change="onPageChange"
            @on-page-size-change="onPageSizeChange"
            show-sizer
            placement="top"
          ></Page>
        </div>
        <Loader :status="list.status" @refresh="getData"></Loader>
      </TabPane>
    </Tabs>
    <BatchEditItem ref="batchEdit" @complete="getData" :idList="idList"></BatchEditItem>
  </Container>
</template>
<script>
import table from '@/table'
import FactoryListData from './list/FactoryListData'
import { clearEmpty, formatDate } from '@/util'
import BatchEditItem from './edit/BatchEditItem'
import StoreSelect from '@/components/StoreSelect'
import SelectList from '@/components/SelectList';
// import { mapGetters } from 'vuex'
export default {
  name: 'report/factory/factoryList',
	components: {
    BatchEditItem,
    StoreSelect,
    SelectList
	},
  data() {
    return {
      tab: 'tab1',
      list: FactoryListData,
      options: {
        tableHeight: 300
      },
      src: '/common/store/listStores',
      // goldPlus: '',
      // goldMinus: '',
      // totalGold: '',
      // totalCount: '',
      // exportRight: true, //导出权限
      // searchRight: true, //搜索权限
      // viewUrls: [
      //   { key: 'exportRight', url: '/sales/gold/record/export' },
      //   { key: 'searchRight', url: '/sales/gold/record/page' }
      // ],
      idList: [],
      departmentTree: []
    }
  },
  computed: {
    exportParam() {
      let param = {
        current: this.list.currentPage,
        size: this.list.pageSize,
        purchOrderSn: this.list.form.purchOrderSn,
        erpOrderSn: this.list.form.erpOrderSn,
        fxDistributorName: this.list.form.fxDistributorName,
        fxDistributorSn: this.list.form.fxDistributorSn,
        fxSn: this.list.form.fxSn,
        receiveAddress: this.list.form.receiveAddress,
        superiorDistributorName: this.list.form.superiorDistributorName,
        receiverContactName: this.list.form.receiverContactName,
        deliveryCo: this.list.form.deliveryCo,
        erpStockOutSn: this.list.form.erpStockOutSn,
        receiverContactPhone: this.list.form.receiverContactPhone,
        title: this.list.form.title,
        deliverySn: this.list.form.deliverySn,
        storeId: this.list.form.storeId,
        deptId: this.list.form.depId,
        parentDeptId: this.list.form.officeId,
        superiorDistributorId: this.list.form.distributorId
      }
      if (this.list.form.date[0] && this.list.form.date[1] && this.list.form.date.length === 2) {
        param.beginTime = formatDate(this.list.form.date[0]) + ' 00:00:00'
        param.endTime = formatDate(this.list.form.date[1]) + ' 23:59:59'
      }
      if (this.list.form.crDate[0] && this.list.form.crDate[1] && this.list.form.crDate.length === 2) {
        param.beginDate = formatDate(this.list.form.crDate[0]) + ' 00:00:00'
        param.endDate = formatDate(this.list.form.crDate[1]) + ' 23:59:59'
      }
      return param
    }
  },
  mounted() {
    this.value = [this.list.form.officeId, this.list.form.depId]
    this.list.currentPage = ~~this.$route.query.currentPage || 1
    this.list.pageSize = ~~this.$route.query.pageSize || this.list.pageSize
    this.$bus.$on('onChangeData', ({val, params, index, type}) => this.onChangeData(val, params, index, type))
    this.$bus.$on('onBlurData', ({params}) => this.onBlurData(params))
    this.initTable()
    this.onSearchBtnClick()
    this.getDptTree()
  },
  destroyed() {
    this.$bus.$off()
  },
  methods: {
    ...table,
    onSearchBtnClick() {
      this.list.currentPage = 1
      this.getData()
    },
    getData() {
      this.idList = []
      // if (!this.searchRight) return
      let param = {
        current: this.list.currentPage,
        size: this.list.pageSize,
        purchOrderSn: this.list.form.purchOrderSn,
        erpOrderSn: this.list.form.erpOrderSn,
        fxDistributorName: this.list.form.fxDistributorName,
        fxDistributorSn: this.list.form.fxDistributorSn,
        fxSn: this.list.form.fxSn,
        receiveAddress: this.list.form.receiveAddress,
        superiorDistributorName: this.list.form.superiorDistributorName,
        receiverContactName: this.list.form.receiverContactName,
        deliveryCo: this.list.form.deliveryCo,
        erpStockOutSn: this.list.form.erpStockOutSn,
        receiverContactPhone: this.list.form.receiverContactPhone,
        title: this.list.form.title,
        deliverySn: this.list.form.deliverySn,
        storeId: this.list.form.storeId,
        deptId: this.list.form.depId,
        parentDeptId: this.list.form.officeId,
        superiorDistributorId: this.list.form.distributorId
      }
      if (this.list.form.date[0] && this.list.form.date[1] && this.list.form.date.length === 2) {
        param.beginTime = formatDate(this.list.form.date[0]) + ' 00:00:00'
        param.endTime = formatDate(this.list.form.date[1]) + ' 23:59:59'
      }
      if (this.list.form.crDate[0] && this.list.form.crDate[1] && this.list.form.crDate.length === 2) {
        param.beginDate = formatDate(this.list.form.crDate[0]) + ' 00:00:00'
        param.endDate = formatDate(this.list.form.crDate[1]) + ' 23:59:59'
      }
      param = clearEmpty(param)
      this.list.status = 'loading'
      this.$jsonPost('/order/direct_delivery/page', param).then(data => {
        this.list.data = []
        this.list.totalItem = Number(data.total)
        this.list.data = (data.records || []).map(item => {
          return {
            id: item.id,
            purchOrderSn: item.purchOrderSn ? item.purchOrderSn : '-', // 单号(中策云)
            fxSn: item.fxSn ? item.fxSn : '-', // 单号(前鹏分销)
            createDate: item.createDate, //创建时间
            deliveryFee: item.deliveryFee ? item.deliveryFee : '0', //直发费用(元)
            deliveryCo: item.deliveryCo ? item.deliveryCo : '-', //快递公司
            deliverySn: item.deliverySn ? item.deliverySn : '-', //快递单号
            storeName: item.storeName ? item.storeName : '-', //门店名称
            storeContact: item.storeContact ? item.storeContact : '-', //门店联系人
            storeContactPhone: item.storeContactPhone ? item.storeContactPhone : '-', //门店电话
            receiveAddress: item.receiveAddress ? item.receiveAddress : '-', //收货地址
            receiverContactName: item.receiverContactName ? item.receiverContactName : '-', //收货人
            receiverContactPhone: item.receiverContactPhone ? item.receiverContactPhone : '-', //收货电话
            superiorDistributorName: item.superiorDistributorName ? item.superiorDistributorName : '-', //上级经销商
            fxDistributorName: item.fxDistributorName ? item.fxDistributorName : '-', //经销商单位名称(前鹏)
            fxDistributorSn: item.fxDistributorSn ? item.fxDistributorSn : '-', //经销商单位编号(前鹏)
            erpOrderSn: item.erpOrderSn ? item.erpOrderSn : '-', //销售订单(ERP)
            erpStockOutSn: item.erpStockOutSn ? item.erpStockOutSn : '-', //出库单(ERP)
            supplierStockoutDate: item.supplierStockoutDate ? item.supplierStockoutDate : '-', //工厂出库时间
            deptName: item.deptName,
            parentDeptName: item.parentDeptName,
            items: (item.items || []).map(child => {
              return {
                id: child.id,
                title: child.title,
                price: child.price,
                quantity: child.quantity
              }
            })
          }
        })
        this.total = data.total
        this.list.status = 'pass'
        this.backTableTop()
      }).catch(() => {
        this.list.status = 'error'
      })
    },
    onBatch() {
      if (!this.idList.length) {
        this.$Message.warning('请先选择')
        return
      }
      this.$refs.batchEdit.updateForm()
    },
    onSelectionChange(selection) {
      this.idList = (selection || []).map(item => item.id)
    },
    onBlurData(params) {
      let param = {
        ids: params.id,
        fee: params.deliveryFee
      }
      this.$ajaxGet('order/direct_delivery/batchUpdate', param).then(data => {
        this.$Notice.success({
          title: '修改成功'
        })
      })
    },
    onChangeData(val, params, index, type) {
      params[type] = val
      this.list[index] = params
    },
    onPageChange(number) {
      this.list.currentPage = number
      this.$router.push({
        name: 'report/factory/factoryList',
        query: {
          currentPage: this.list.currentPage,
          pageSize: this.list.pageSize
        }
      })
      this.getData()
    },
    onPageSizeChange(pageSize) {
      this.list.currentPage = 1
      this.list.pageSize = pageSize
      this.$router.push({
        name: 'report/factory/factoryList',
        query: {
          currentPage: this.list.currentPage,
          pageSize: this.list.pageSize
        }
      })
      this.getData()
    },
    getDptTree() {
      this.$jsonPost('department/listDepartmentTree').then(res => {
        const func = (arr) => {
          arr.forEach(item => {
            item.label = item.name
            item.value = item.id
            if(item.children && item.children.length) {
              func(item.children)
            }
          })
        }
        func(res)
        this.departmentTree = res
      })
    },
    onSelectDpt(val) {
      let [d, a] = val
      this.list.form.officeId = d
      this.list.form.depId = a
      // if (a) {
      //   delete this.list.form.officeId
      // }
      let id = val[val.length-1]
      if(!id) return
      let obj = {
        departId: id,
        current: 1,
        size: 9999,
        isPage: false
      }
      this.$refs.dealerList.getListDispath('getDealerListByDpt', obj)
    }
  },
  watch: {
    $route() {
      let page = ~~this.$route.query.currentPage
      let table = this.list
      if (table.currentPage !== page) {
        table.currentPage = ~~this.$route.query.currentPage === 0 ? 1 : ~~this.$route.query.currentPage
        this.getData()
      }
    }
  }
}
</script>